<template>
  <ProTable ref="proTable" :requestApi="getUserList" :columns="columns" :extraSearch="extraSearch" :toolButton="false">
    <!-- 表格 header 按钮 -->
    <template #tableHeader>
      <el-button type="primary" :icon="Plus" @click="openDrawer()">新增用户</el-button>
    </template>
    <!-- 用户状态 slot -->
    <template #status="scope">
      <!-- 如果插槽的值为 el-switch，第一次加载会默认触发 switch 的 @change 方法，所有在外层包一个盒子，点击触发盒子 click 方法 -->
      <div @click="changeStatus(scope.row)">
        <el-switch
          :value="scope.row.status"
          :active-text="scope.row.status === 1 ? '启用' : '禁用'"
          :active-value="1"
          :inactive-value="0"
        />
      </div>
    </template>
    <template #login_times="scope">
      <span>{{ scope.row.user_data ? scope.row.user_data.login_times : 0 }}</span>
    </template>
    <template #last_login_ip="scope">
      <span>{{ scope.row.user_data ? scope.row.user_data.last_login_ip : '--' }}</span>
    </template>
    <template #last_login_time="scope">
      <span>{{ scope.row.user_data ? scope.row.user_data.last_login_time : '--' }}</span>
    </template>
    <!-- 表格操作 -->
    <template #operation="scope">
      <el-button type="primary" link :icon="EditPen" @click="doEdit( scope.row)">编辑</el-button>
      <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
    </template>
  </ProTable>
  <el-dialog
    v-model="dialogInfo.show"
    :title="formItem.id === 0 ? '新增用户' : '编辑用户'"
    width="40%"
    top="30px"
    @close="doCancel(formRef)"
  >
    <el-form
      ref="formRef"
      :model="formItem"
      :rules="rules"
      label-width="120px"
      status-icon
    >
      <el-form-item label="用户账号" prop="username">
        <el-input v-model="formItem.username" />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="formItem.nickname" />
      </el-form-item>
      <el-form-item label="用户密码" prop="password">
        <el-input v-model="formItem.password" type="password" />
      </el-form-item>
      <el-form-item label="权限组" prop="group_id">
        <el-checkbox-group v-model="formItem.group_id">
          <el-checkbox v-for="(item, i) in groupList" :key="i" :label="item.id">{{ item.name }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogInfo.show = false">取消</el-button>
        <el-button type="primary" @click="submit(formRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";
import {getUserList, changeUserStatus, deleteUser, addUser, editUser} from "@/api/modules/user";
import {getGroups} from "@/api/modules/auth";
import {Plus, EditPen, Delete} from "@element-plus/icons-vue";
import {useHandleData} from "@/hooks/useHandleData";
import {statusType} from "@/utils/serviceDict";
import {ColumnProps} from "@/components/ProTable/interface";
import ProTable from "@/components/ProTable/index.vue";
import {User} from "@/api/interface";
import {ElForm, ElMessage} from "element-plus";

type FormInstance = InstanceType<typeof ElForm>
const formRef = ref<FormInstance>()

const dialogInfo = reactive({
	show: false
})
const proTable = ref();
const searchType = [
	{label: "用户账号", value: 1},
	{label: "用户昵称", value: 2}
]
const formItem = reactive({
	id: 0,
	username: '',
	nickname: '',
	password: '',
	group_id: []
})
const rules = reactive({
	username: [
		{ required: true, message: '用户账号不能为空', trigger: 'blur' }
	],
	nickname: [
		{ required: true, message: '用户昵称不能为空', trigger: 'blur' }
	],
	password: [
		{ required: true, message: '用户密码不能为空', trigger: 'blur' }
	]
})
const groupList = ref();

const columns: Partial<ColumnProps>[] = [
	{
		type: "index",
		label: "#",
		width: 80
	},
	{
		prop: "username",
		label: "用户账号"
	},
	{
		prop: "nickname",
		label: "用户昵称",
		width: 160
	},
	{
		prop: "login_times",
		label: "登录次数",
		width: 100
	},
	{
		prop: "last_login_time",
		label: "最后登录时间",
		width: 170
	},
	{
		prop: "last_login_ip",
		label: "最后登录IP",
		width: 160
	},
	{
		prop: "status",
		label: "用户状态",
		enum: statusType,
		search: true,
		searchType: 'select',
		width: 160
	},
	{
		prop: "operation",
		label: "操作",
		width: 200,
		fixed: "right"
	}
];
const extraSearch: Partial<ColumnProps>[] = [
	{
		prop: "type",
		label: "搜索类别",
		enum: searchType,
		searchType: 'select'
	},
	{
		prop: "keywords",
		label: "关键词"
	}
];

onMounted(() => {
	getGroups().then(res => {
		groupList.value = res.data?.list
	})
})

// 切换用户状态
const changeStatus = async (row: User.ResUserList) => {
	await useHandleData(changeUserStatus, {id: row.id, status: row.status == 1 ? 0 : 1}, `切换【${row.username}】用户状态`);
	proTable.value.refresh();
};
const deleteAccount = async (row: User.ResUserList) => {
	await useHandleData(deleteUser, {id: row.id}, `删除【${row.username}】用户`);
	proTable.value.refresh();
}
const openDrawer = () => {
	dialogInfo.show = true
}
const doEdit = (row: User.ResUserList) => {
	formItem.id = Number(row.id)
	formItem.username = row.username
	formItem.nickname = row.nickname
	formItem.password = 'ApiAdmin'

	if (row.group_id) {
		formItem.group_id = row.group_id.map(item => {
			return +item;
		});
	}
	openDrawer()
}
const doCancel = (formEl: FormInstance | undefined) => {
	formEl?.resetFields()
	formItem.id = 0
}
const submit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate(async valid => {
		if (valid) {
			let res
			if (formItem.id === 0) {
				res = await addUser(formItem)
			} else {
				res = await editUser(formItem)
			}
			proTable.value.refresh()
			ElMessage.success(res.msg)
			dialogInfo.show = false
		}
	})
}
</script>
